<template>
  <div class="data-domain-management">
    <div class="page-header">
      <h1>数据域管理</h1>
      <p class="page-description">管理数据域定义，为数据字段提供标准化的业务分类和规范</p>
    </div>

    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="showCreateDialog" :icon="Plus">
          新建数据域
        </el-button>
        <el-button @click="refreshData" :icon="Refresh" :loading="loading">
          刷新
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索数据域名称或编码"
          :prefix-icon="Search"
          clearable
          style="width: 300px"
        />
      </div>
    </div>

    <el-table
      :data="filteredDataDomains"
      v-loading="loading"
      stripe
      style="width: 100%"
    >
      <el-table-column prop="code" label="数据域编码" width="150" />
      <el-table-column prop="name" label="数据域名称" width="200" />
      <el-table-column prop="description" label="描述" min-width="250" />
      <el-table-column prop="category" label="业务分类" width="120">
        <template #default="{ row }">
          <el-tag :type="getCategoryType(row.category)">{{ row.category }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editDataDomain(row)">
            编辑
          </el-button>
          <el-button 
            :type="row.status === 'active' ? 'warning' : 'success'" 
            size="small" 
            @click="toggleStatus(row)"
          >
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="small" @click="deleteDataDomain(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建/编辑数据域对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据域' : '新建数据域'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="数据域编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入数据域编码，如：USER、PRODUCT"
            :disabled="isEdit"
          />
          <div class="form-tip">编码用于系统内部标识，建议使用英文大写字母</div>
        </el-form-item>
        
        <el-form-item label="数据域名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入数据域名称，如：用户域、商品域"
          />
        </el-form-item>
        
        <el-form-item label="业务分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择业务分类" style="width: 100%">
            <el-option label="核心业务" value="core" />
            <el-option label="支撑业务" value="support" />
            <el-option label="管理业务" value="management" />
            <el-option label="外部接口" value="external" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据域的详细描述"
          />
        </el-form-item>
        
        <el-form-item label="负责人">
          <el-input
            v-model="formData.owner"
            placeholder="请输入负责人姓名"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref()

// 数据域列表
const dataDomains = ref([
  {
    id: 1,
    code: 'USER',
    name: '用户域',
    description: '用户相关的所有数据，包括用户基本信息、账户信息、权限信息等',
    category: 'core',
    status: 'active',
    owner: '张三',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    code: 'PRODUCT',
    name: '商品域',
    description: '商品相关的所有数据，包括商品基本信息、分类、库存、价格等',
    category: 'core',
    status: 'active',
    owner: '李四',
    createTime: '2024-01-15 11:00:00',
    updateTime: '2024-01-15 11:00:00'
  },
  {
    id: 3,
    code: 'ORDER',
    name: '订单域',
    description: '订单相关的所有数据，包括订单信息、支付信息、物流信息等',
    category: 'core',
    status: 'active',
    owner: '王五',
    createTime: '2024-01-15 11:30:00',
    updateTime: '2024-01-15 11:30:00'
  },
  {
    id: 4,
    code: 'SYSTEM',
    name: '系统域',
    description: '系统管理相关的数据，包括配置信息、日志信息、监控数据等',
    category: 'management',
    status: 'active',
    owner: '赵六',
    createTime: '2024-01-15 12:00:00',
    updateTime: '2024-01-15 12:00:00'
  }
])

// 表单数据
const formData = reactive({
  code: '',
  name: '',
  description: '',
  category: '',
  status: 'active',
  owner: ''
})

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入数据域编码', trigger: 'blur' },
    { pattern: /^[A-Z][A-Z0-9_]*$/, message: '编码只能包含大写字母、数字和下划线，且以大写字母开头', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入数据域名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择业务分类', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const filteredDataDomains = computed(() => {
  if (!searchKeyword.value) {
    return dataDomains.value
  }
  return dataDomains.value.filter(domain => 
    domain.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    domain.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const getCategoryType = (category) => {
  const types = {
    core: 'primary',
    support: 'success',
    management: 'warning',
    external: 'info'
  }
  return types[category] || 'info'
}

const formatDateTime = (dateTime) => {
  return dateTime
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const editDataDomain = (domain) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(formData, {
    id: domain.id,
    code: domain.code,
    name: domain.name,
    description: domain.description,
    category: domain.category,
    status: domain.status,
    owner: domain.owner
  })
}

const resetForm = () => {
  Object.assign(formData, {
    code: '',
    name: '',
    description: '',
    category: '',
    status: 'active',
    owner: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 更新数据域
      const index = dataDomains.value.findIndex(d => d.id === formData.id)
      if (index !== -1) {
        dataDomains.value[index] = {
          ...dataDomains.value[index],
          ...formData,
          updateTime: new Date().toLocaleString()
        }
      }
      ElMessage.success('数据域更新成功')
    } else {
      // 创建数据域
      const newDomain = {
        id: Date.now(),
        ...formData,
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
      dataDomains.value.push(newDomain)
      ElMessage.success('数据域创建成功')
    }
    
    dialogVisible.value = false
  } catch {
    ElMessage.warning('请完善表单信息')
  } finally {
    submitting.value = false
  }
}

const toggleStatus = async (domain) => {
  try {
    await ElMessageBox.confirm(
      `确定要${domain.status === 'active' ? '禁用' : '启用'}数据域 "${domain.name}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    domain.status = domain.status === 'active' ? 'inactive' : 'active'
    domain.updateTime = new Date().toLocaleString()
    ElMessage.success(`数据域已${domain.status === 'active' ? '启用' : '禁用'}`)
  } catch {
    // 用户取消
  }
}

const deleteDataDomain = async (domain) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据域 "${domain.name}" 吗？删除后不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = dataDomains.value.findIndex(d => d.id === domain.id)
    if (index !== -1) {
      dataDomains.value.splice(index, 1)
      ElMessage.success('数据域删除成功')
    }
  } catch {
    // 用户取消
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('数据刷新成功')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 组件挂载时可以加载数据
})
</script>

<style scoped>
.data-domain-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  text-align: right;
}
</style>